package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.SystemSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class HomeResource {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private SystemSetting systemSetting;

    public HomeResource(){

    }

    @GetMapping("/home/getServiceDateTime")
    @Timed
    public String getServiceDateTime() {
        return simpleDateFormat.format(new Date()).toString();
    }

    @GetMapping("/connect/test")
    @Timed
    public String connectTest() {
        return "连接成功";
    }

    @GetMapping("/config/gps")
    @Timed
    public String getGpsConfig(){
        if(systemSetting !=null){
            return JSON.toJSONString(systemSetting);
        }
        else {
            return null;
        }
    }

    @GetMapping("/arcgis/sendPost")
    @Timed
    public String sendPost(){
        String para = "username=arcgis&password=arcgisadmin&user_orgkey=''&oauth_state=LZTEn_qz6WMVHzbyWCz37r2bfRF5Si3f-ZBBznbSjHMg1UoRTYCRmIInfBcT6WyaOgBleo2vy2LAO7XXayfGQ4iC0SlHAv0dmkEUj1E9XOKoJJjtVhsfJGOfRtuMFUgLHgXc9TY08WAvyQvWy7Uvet_vk5tANIExyEGbB68aOtNGU1jxAzzz5-o9Nlf-Lv-ZOpWsZvPrqQr9qAzkyZzainTa4AajpyApclOBN9wxUe0on9e0l3QLwp-XdHsgElRB-VGypdxtevKDV5OAu6mrDQ..";
        String result = sendPost("http://192.168.1.179/arcgis/sharing/oauth2/signin", para);
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
//            conn.addRequestProperty("Host", realUrl.getHost());//设置头信息
//            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "close");
//            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("cookie", "dsfewefwf");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //1.获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //2.中文有乱码的需要将PrintWriter改为如下
            //out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            Map<String, List<String>> headers = conn.getHeaderFields();
            System.out.println("header结果："+headers);
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            String cookie = conn.getHeaderField("Set-Cookie");
            System.out.println("read over" + cookie);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        System.out.println("post推送结果："+result);
        return result;
    }

}
